package com.ztesoft.zsmart.zcm.monitor.utils;

import com.ztesoft.zsmart.zcm.monitor.config.MonitorProperties;

import java.math.BigDecimal;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public final class GeneralThreadPoolExecutorUtil {
    private GeneralThreadPoolExecutorUtil() {
    }

    private static final int poolSize = SpringContextUtil.getBean(MonitorProperties.class)
        .getSystemGeneralThreadPoolSize();

    private static final int maxPoolSize = SpringContextUtil.getBean(MonitorProperties.class)
        .getSystemGeneralThreadMaxPoolSize();

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, maxPoolSize, 1, TimeUnit.MINUTES,
        new LinkedBlockingQueue<Runnable>(3000), new NamedThreadFactory("systemGeneralThreadPoolExecutor"));

    public static ThreadPoolExecutor getExecutor() {
        return executor;
    }

    public static int getThreadNum(int threadNum, int taskTotal, int splitNum) {
        if (taskTotal > splitNum) {
            BigDecimal[] divideAndRemainder = new BigDecimal(taskTotal)
                .divideAndRemainder(new BigDecimal(splitNum + ""));
            BigDecimal s = divideAndRemainder[1];
            BigDecimal y = divideAndRemainder[0];
            if (s.intValue() != 0) {
                threadNum = y.add(BigDecimal.ONE).intValue();
            }
            else if (y.intValue() != 0) {
                threadNum = y.intValue();
            }
        }
        return threadNum;
    }
}
